package com.qf.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.qf.common.R;
import com.qf.dto.UserRoleDto;
import com.qf.mapper.AdminMapper;
import com.qf.mapper.StudentMapper;
import com.qf.mapper.TeacherMapper;
import com.qf.mapper.impl.AdminMapperImpl;
import com.qf.mapper.impl.StudentMapperImpl;
import com.qf.mapper.impl.TeacherMapperImpl;
import com.qf.pojo.Admin;
import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.utils.CookieUtils;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class UserServiceImpl implements UserService {

    private StudentMapper studentMapper = new StudentMapperImpl();
    private TeacherMapper teacherMapper = new TeacherMapperImpl();
    private AdminMapper adminMapper = new AdminMapperImpl();

    @Override
    public void drawCode(HttpServletRequest request, HttpServletResponse response) {
        //设置宽高的变量
        int width = 120;
        int height = 30;

        //创建画布
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //获取画笔
        Graphics graphics = image.getGraphics();

        //设置背景色 -- 填充矩形
        graphics.setColor(Color.BLUE);
        graphics.fillRect(0, 0, width, height);

        //设置验证码
        Random random = new Random();
        String[] codes = {"A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
        Color[] colors = {Color.CYAN, Color.BLACK, Color.GREEN, Color.PINK, Color.WHITE, Color.RED, Color.ORANGE};

        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < 4; i++) {

            String randomCode = codes[random.nextInt(codes.length)];
            Color randomColor = colors[random.nextInt(colors.length)];

            graphics.setColor(randomColor);//设置随机颜色
            graphics.setFont(new Font("宋体", Font.BOLD, 20 + random.nextInt(10)));//设置字体（字体,样式,大小）
            graphics.drawString(randomCode, 20 + i * 25, 15 + random.nextInt(10));//设置单个验证码

            sb.append(randomCode);
        }

        //将系统验证码设置到Session对象中(会话对象)
        HttpSession session = request.getSession();//获取请求里的JSESSIONID(客户端Cookie里的数据)，如果没有就创建Session对象，如果有就从Session容器中获取会话对象
        session.setAttribute("sysCode", sb.toString());

        //设置干扰线
        graphics.setColor(Color.YELLOW);
        for (int i = 0; i < 3; i++) {
            graphics.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));//绘制直线(x1,y1,x2,y2) -> 两点为一线
        }

        //将画布以jpg形式的文件传出给客户端
        try {
            ImageIO.write(image, "jpg", response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取请求中的数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String userCode = request.getParameter("userCode");
        String rememberMe = request.getParameter("rememberMe");
        String role = request.getParameter("role");
        //从Session对象中获取系统的验证码
        String sysCode = (String) request.getSession().getAttribute("sysCode");
        if (sysCode.equalsIgnoreCase(userCode)) {//验证码正确
            User user = null;
            Admin admin = null;
            if ("student".equals(role)) {
                user = studentMapper.getStudent(username, password);
            } else if ("teacher".equals(role)) {
                user = teacherMapper.getTeacher(username, password);
            } else if ("admin".equals(role)) {
                admin = adminMapper.getAdmin(username, password);
            }
            if (user != null || admin != null) {//登录成功
                //判断是否记住我
                if (rememberMe != null) {
                    if ("admin".equals(role)) {
                        rememberAdmin(request, response, username, role);
                    } else {
                        rememberMe(request, response, user.getUsername(), user.getName(), role, user.getPhoto());
                    }
                }
                HttpSession session = request.getSession();
                session.setAttribute("role", role);
                UserRoleDto userRoleDto = new UserRoleDto();
                if ("admin".equals(role)) {
                    session.setAttribute("user", admin);
                    userRoleDto.setUsername(admin.getUsername());
                    userRoleDto.setRole(role);
                    userRoleDto.setName(admin.getUsername());
                    response.getWriter().write(JSONArray.toJSONString(R.success("登录成功", userRoleDto)));
                } else {
                    session.setAttribute("user", user);
                    userRoleDto.setUsername(user.getUsername());
                    userRoleDto.setRole(role);
                    userRoleDto.setName(user.getName());
                    userRoleDto.setPhoto(user.getPhoto());
                    response.getWriter().write(JSONArray.toJSONString(R.success("登录成功", userRoleDto)));
                }
            } else {//登录失败 -- 账号或密码错误
                response.getWriter().write(JSON.toJSONString(R.fail("登录失败 -- 账号或密码错误")));
            }

        } else {//登录失败 - 验证码错误
            response.getWriter().write(JSON.toJSONString(R.fail("登录失败 -- 验证码错误")));
        }
    }

    @Override
    public void rememberMe(HttpServletRequest request, HttpServletResponse response, String username, String name, String role, String photo) {
        //将凭证添加到Cookie中
        response.addCookie(CookieUtils.createCookie("username", username, 60 * 60 * 24 * 5));
        response.addCookie(CookieUtils.createCookie("name", name, 60 * 60 * 24 * 5));
        response.addCookie(CookieUtils.createCookie("role", role, 60 * 60 * 24 * 5));
        response.addCookie(CookieUtils.createCookie("photo", photo, 60 * 60 * 24 * 5));
    }

    @Override
    public void rememberAdmin(HttpServletRequest request, HttpServletResponse response, String username, String role) {
        //将凭证添加到Cookie中
        response.addCookie(CookieUtils.createCookie("username", username, 60 * 60 * 24 * 5));
        response.addCookie(CookieUtils.createCookie("name", username, 60 * 60 * 24 * 5));
        response.addCookie(CookieUtils.createCookie("role", role, 60 * 60 * 24 * 5));
    }

    @Override
    public void loginOut(HttpServletRequest request, HttpServletResponse response) {
        //删除Cookie里的数据
        response.addCookie(CookieUtils.createCookie("username", "", 0));
        response.addCookie(CookieUtils.createCookie("name", "", 0));
        response.addCookie(CookieUtils.createCookie("role", "", 0));
        response.addCookie(CookieUtils.createCookie("photo", "", 0));

        //删除Session里的数据
        HttpSession session = request.getSession();
        session.removeAttribute("username");
        session.removeAttribute("name");
        session.removeAttribute("role");
        session.removeAttribute("photo");
    }

    @Override
    public void resetPassword(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取请求中的数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String newPassword = request.getParameter("newPassword");
        String role = request.getParameter("role");

        User user = null;
        Admin admin = null;
        if ("student".equals(role)) {
            user = studentMapper.getStudent(username, password);
        } else if ("teacher".equals(role)) {
            user = teacherMapper.getTeacher(username, password);
        } else if ("admin".equals(role)) {
            admin = adminMapper.getAdmin(username, password);
        }

        if (user != null || admin != null) {
            if ("student".equals(role)) {
                studentMapper.update(username, newPassword);
            } else if ("teacher".equals(role)) {
                teacherMapper.update(username, newPassword);
            } else if ("admin".equals(role)) {
                adminMapper.update(username, newPassword);
            }
            response.getWriter().write(JSON.toJSONString(R.success("重置密码成功", null)));
        } else {
            response.getWriter().write(JSON.toJSONString(R.fail("重置密码失败 -- 密码错误")));
        }


    }


}
